import axios from 'axios'
import { createDiscreteApi } from 'naive-ui'
import { useLoadingStore, userTokenStore } from '@/stores'
import router from '@/router'
const loadingStore = useLoadingStore()
const tokenStore = userTokenStore()
export const baseURL = 'http://127.0.0.1:8080'
const { message, loadingBar, dialog } = createDiscreteApi(['message', 'loadingBar', 'dialog'])
const _axios = axios.create({
	baseURL
})
_axios.interceptors.request.use(config => {
	if (config.method === 'post') {
		const formData = new FormData()
		const params = config.params
		for (const key in params) {
			if (params[key] instanceof Array) {
				for (const i in params[key]) {
					formData.append(key, params[key][i])
				}
			} else {
				formData.append(key, params[key])
			}
		}
		config.data = formData
		delete config.params
	}
	return config
})
_axios.interceptors.response.use(response => {
	if (response.data.code === 200) {
		if (response.data.message) {
			message.success(response.data.message)
		}
		return response.data.content
	} else {
		if (response.data.code === 401) {
			tokenStore.setToken(null)
			router.push('/login')
		}
		return Promise.reject(response.data.message)
	}
}, error => {
	return Promise.reject('网络异常')
})
export const request = (url, method, params, callback) => {
	const axios_config = {
		url,
		method,
		params
	}
	loadingBar.start()
	loadingStore.openLoading()
	_axios.request(axios_config).then(content => {
		callback(content)
		loadingStore.closeLoading()
	}).catch(error => {
		console.dir(error)
		message.error(error)
		loadingStore.closeLoading()
	}).finally(() => {
		loadingBar.finish()
	})
}
export const get = (url, params, callback) => { request(url, 'get', params, callback) }
export const post = (url, params, callback, formObj = null) => {
	if (formObj) {
		formObj.validate(errors => {
			if (!errors) {
				request(url, 'post', params, callback) 
			}
		}).catch(error => {
			console.dir(error)
		})
	} else {
		request(url, 'post', params, callback)
	}
}
export const del = (url, params, callback) => {
	dialog.warning({
		title: '警告',
		content: '确定要删除吗？',
		positiveText: '确定',
		negativeText: '取消',
		draggable: true,
		onPositiveClick: () => {
			post(url, params, callback)
		},
		onNegativeClick: () => {
			message.error('取消删除')
		}
	})
}